import 'dart:ui';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:kudos/config/widget_config.dart';
import 'package:kudos/core/utils/kudo_helper.dart';
import '../../utils/kudo_colors.dart';
import '../../utils/image_resource_helper.dart';
import '../../widget/login_required_dialog.dart';
import '../../widget/report_dialog.dart';
import '../../state/person/persona_session_controller.dart';
import '../../state/person/persona_entity.dart';
import '../../state/person/persona_follow_controller.dart';
import '../../state/team/kite_team_controller.dart';
import '../../state/team/kite_team_entity.dart';
import '../../router/app_navigation_manager.dart';
import '../../state/topic/kite_topic_controller.dart';
import '../../state/topic/kite_topic_entity.dart';
import '../../state/exchange/kite_exchange_controller.dart';
import '../../state/exchange/kite_exchange_entity.dart';

class GatheringScreen extends StatefulWidget {
  const GatheringScreen({super.key});

  @override
  State<GatheringScreen> createState() => _GatheringScreenState();
}

class _GatheringScreenState extends State<GatheringScreen> {
  late PageController _pageController;
  int _currentTabIndex = 0;

  final TextEditingController _teamDescriptionController =
      TextEditingController();
  final TextEditingController _teamLocationController = TextEditingController();

  @override
  void initState() {
    super.initState();
    _pageController = PageController();
    KiteExchangeController.globalInstance.getAllKiteExchanges();
  }

  @override
  void dispose() {
    _pageController.dispose();
    _teamDescriptionController.dispose();
    _teamLocationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/main_background.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: SingleChildScrollView(
          child: SafeArea(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                _buildPopularUsersSection(),
                SizedBox(height: 24.h),
                _buildTeamKiteFlyingSection(),
                SizedBox(height: 24.h),
                _buildTabSection(),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildPopularUsersSection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('Popular Users')
            .fontSize(28.sp)
            .fontWeight(FontWeight.w900)
            .fontFamily(
              GoogleFonts.montserrat(fontWeight: FontWeight.w900).fontFamily,
            )
            .textColor(KudoColors.black)
            .textShadow(
              color: KudoColors.yellow,
              blurRadius: 0,
              offset: const Offset(0, 4),
            )
            .fontFamily(GoogleFonts.lato().fontFamily)
            .paddingHorizontal(16.w),

        SizedBox(height: 16.h),

        Builder(
          builder: (context) {
            final currentUser = PersonaSessionController
                .globalInstance
                .currentPersonaState
                .reactiveValue(context);
            final allUsers = PersonaEntity.getDefaultKiteUsers();
            final otherUsers =
                allUsers
                    .where(
                      (user) =>
                          currentUser == null ||
                          user.uniqueIdentifier != currentUser.uniqueIdentifier,
                    )
                    .toList();

            return SizedBox(
              height: 73.h,
              child: ListView.builder(
                scrollDirection: Axis.horizontal,
                itemCount: otherUsers.length,
                itemBuilder: (context, index) {
                  return _buildUserItem(otherUsers[index]);
                },
              ).paddingHorizontal(0.w),
            );
          },
        ),
      ],
    );
  }

  Widget _buildUserItem(PersonaEntity user) {
    return Container(
      width: 80.w,
      height: 70.h,
      margin: EdgeInsets.only(right: 3.w),
      child: Stack(
        clipBehavior: Clip.none,
        children: [
          Positioned(
            top: 0,
            left: 0,
            right: 0,
            child: Center(
              child: GestureDetector(
                onTap: () => _handleUserAvatarTap(user),
                child: ImageResourceHelper.buildCircularAvatar(
                  imagePath: user.avatarResourceUrl,
                  radius: 27.r,
                ),
              ),
            ),
          ),

          Positioned(
            top: 27.r + 12.h,
            left: 0,
            right: 0,
            child: Builder(
              builder: (context) {
                final isFollowing = PersonaFollowController.globalInstance
                    .getFollowStatusState(user.uniqueIdentifier)
                    .reactiveValue(context);
                return Center(
                  child: Text(isFollowing ? 'Followed' : '+Follow')
                      .fontSize(14.sp)
                      .fontWeight(FontWeight.w400)
                      .textColor(KudoColors.black)
                      .italic()
                      .fontFamily(GoogleFonts.lato().fontFamily)
                      .paddingHorizontal(8.w)
                      .paddingVertical(4.h)
                      .parent(
                        ({required Widget child}) => Container(
                          decoration: BoxDecoration(
                            color: KudoColors.yellow,
                            borderRadius: BorderRadius.circular(11.r),
                          ),
                          child: child,
                        ),
                      )
                      .configWidget(borderRadius: 11.r)
                      .inkWell(
                        onTap: () => _handleFollowUser(user.uniqueIdentifier),
                      ),
                );
              },
            ),
          ),
        ],
      ),
    );
  }

  void _handleFollowUser(String userId) {
    final currentUser =
        PersonaSessionController.globalInstance.currentPersonaState.value;
    if (currentUser == null) {
      LoginRequiredDialog.show(
        context: context,
        title: 'Login Required',
        message: 'Please login to follow users',
      );
      return;
    }

    final isFollowing =
        PersonaFollowController.globalInstance
            .getFollowStatusState(userId)
            .value;

    if (isFollowing) {
      KudoToast.showSuccessToast(context, 'Unfollowed successfully');
      PersonaFollowController.quickUnfollowPersona(userId);
    } else {
      KudoToast.showSuccessToast(context, 'Followed successfully');
      PersonaFollowController.quickFollowPersona(userId);
    }
  }

  Widget _buildTeamKiteFlyingSection() {
    return Column(
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text('Team Kite Flying')
                .fontSize(24.sp)
                .fontWeight(FontWeight.bold)
                .textColor(KudoColors.black)
                .fontFamily(GoogleFonts.lato().fontFamily),

            Text('Create A Team')
                .fontSize(12.sp)
                .fontWeight(FontWeight.w900)
                .textColor(KudoColors.black)
                .fontFamily(GoogleFonts.lato().fontFamily)
                .paddingHorizontal(10.w)
                .paddingVertical(6.h)
                .parent(
                  ({required Widget child}) => Container(
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(24.r),
                    ),
                    child: child,
                  ),
                )
                .configWidget(borderRadius: 24.r)
                .inkWell(onTap: _showCreateTeamDialog),
          ],
        ).paddingHorizontal(16.w),

        SizedBox(height: 16.h),

        SizedBox(
          height: 294.h,
          child: ListView.builder(
            itemCount: KiteTeamController.globalInstance.getAllTeams().length,
            itemBuilder: (context, index) {
              final teams = KiteTeamController.globalInstance.getAllTeams();
              return _buildTeamItem(teams[index]);
            },
          ).paddingHorizontal(16.w),
        ),
      ],
    );
  }

  Widget _buildTeamItem(KiteTeamEntity team) {
    return Container(
      width: 343.w,
      height: 90.h,
      margin: EdgeInsets.only(bottom: 12.h),
      decoration: const BoxDecoration(
        image: DecorationImage(
          image: AssetImage('assets/images/team_card_background.png'),
          fit: BoxFit.fill,
        ),
      ),
      child: Row(
        children: [
          _buildTeamCreatorAvatar(team.creatorPersonaId).alignTop(),

          SizedBox(width: 12.w),

          Expanded(
            child: Padding(
              padding: EdgeInsets.only(bottom: 6.w, top: 6.h, right: 12.w),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const Spacer(),
                  Row(
                    children: [
                      _buildTeamCreatorName(team.creatorPersonaId),
                      SizedBox(width: 8.w),
                      Icon(
                        Icons.location_on,
                        size: 12.sp,
                        color: KudoColors.black,
                      ),
                      SizedBox(width: 2.w),
                      Text(team.locationInfo)
                          .fontSize(12.sp)
                          .textColor(KudoColors.black)
                          .fontFamily(GoogleFonts.lato().fontFamily),
                      const Spacer(),
                      _buildJoinTeamButton(team),
                    ],
                  ),

                  const Spacer(),

                  Text(team.teamDescription)
                      .fontSize(11.sp)
                      .textColor(KudoColors.black)
                      .fontFamily(GoogleFonts.lato().fontFamily),

                  const Spacer(),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildTeamCreatorAvatar(String creatorId) {
    final creator = PersonaSessionController.quickGetUserById(creatorId);
    return GestureDetector(
      onTap: () {
        if (creator != null) {
          _handleUserAvatarTap(creator);
        }
      },
      child: ImageResourceHelper.buildCircularAvatar(
        imagePath: creator?.avatarResourceUrl ?? '',
        radius: 27.r,
      ).configWidget(borderRadius: 200.r),
    );
  }

  Widget _buildTeamCreatorName(String creatorId) {
    final creator = PersonaSessionController.quickGetUserById(creatorId);
    return Text(creator?.displayAlias ?? 'Unknown')
        .fontSize(14.sp)
        .fontWeight(FontWeight.bold)
        .textColor(KudoColors.black)
        .fontFamily(GoogleFonts.lato().fontFamily);
  }

  Widget _buildJoinTeamButton(KiteTeamEntity team) {
    final currentUser = PersonaSessionController
        .globalInstance
        .currentPersonaState
        .reactiveValue(context);
    final isJoined =
        currentUser != null && team.isUserMember(currentUser.uniqueIdentifier);

    return Text(isJoined ? 'Chat' : 'Join In>')
        .fontSize(14.sp)
        .fontWeight(FontWeight.w400)
        .textColor(KudoColors.yellow)
        .italic()
        .fontFamily(GoogleFonts.lato().fontFamily)
        .paddingHorizontal(8.w)
        .paddingVertical(2.h)
        .parent(
          ({required Widget child}) => Container(
            decoration: BoxDecoration(
              color: KudoColors.black,
              borderRadius: BorderRadius.circular(12.r),
            ),
            child: child,
          ),
        )
        .inkWell(onTap: () => _handleJoinTeam(team));
  }

  void _handleJoinTeam(KiteTeamEntity team) {
    final currentUser = PersonaSessionController
        .globalInstance
        .currentPersonaState
        .reactiveValue(context);
    if (currentUser == null) {
      LoginRequiredDialog.show(
        context: context,
        title: 'Login Required',
        message: 'Please login to join teams',
      );
      return;
    }

    final isJoined = team.isUserMember(currentUser.uniqueIdentifier);
    if (isJoined) {
      AppNavigationManager.navigateToKiteTeamChat(context, team);
    } else {
      _showJoinTeamConfirmDialog(team);
    }
  }

  void _showJoinTeamConfirmDialog(KiteTeamEntity team) {
    showDialog(
      context: context,
      barrierColor: Colors.black.withValues(alpha: 0.5),
      builder:
          (context) => Dialog(
            backgroundColor: Colors.transparent,
            child: Container(
              width: MediaQuery.of(context).size.width - 32.w,
              decoration: BoxDecoration(
                color: KudoColors.green,
                borderRadius: BorderRadius.circular(24.r),
              ),
              child: Stack(
                children: [
                  Padding(
                    padding: EdgeInsets.all(24.w),
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        SizedBox(height: 20.h),
                        Builder(
                          builder: (context) {
                            final creator =
                                PersonaSessionController.quickGetUserById(
                                  team.creatorPersonaId,
                                );
                            final creatorName =
                                creator?.displayAlias ?? 'Unknown';
                            return Text(
                              'Do You Want To Join $creatorName\'s Team?',
                              textAlign: TextAlign.center,
                              style: GoogleFonts.lato(
                                fontSize: 16.sp,
                                fontWeight: FontWeight.w400,
                                color: KudoColors.black,
                              ),
                            );
                          },
                        ),

                        SizedBox(height: 32.h),

                        Row(
                          children: [
                            Expanded(
                              child: Container(
                                height: 48.h,
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(20.r),
                                  border: Border.all(
                                    color: KudoColors.yellow,
                                    width: 2.w,
                                  ),
                                ),
                                child: TextButton(
                                  onPressed: () => Navigator.of(context).pop(),
                                  style: TextButton.styleFrom(
                                    shape: RoundedRectangleBorder(
                                      borderRadius: BorderRadius.circular(20.r),
                                    ),
                                  ),
                                  child: Text(
                                    'Cancel',
                                    style: GoogleFonts.lato(
                                      fontSize: 16.sp,
                                      fontWeight: FontWeight.bold,
                                      color: KudoColors.yellow,
                                    ),
                                  ),
                                ),
                              ),
                            ),

                            SizedBox(width: 16.w),

                            Expanded(
                              child: Container(
                                height: 48.h,
                                decoration: BoxDecoration(
                                  color: KudoColors.yellow,
                                  borderRadius: BorderRadius.circular(20.r),
                                  boxShadow: [
                                    BoxShadow(
                                      color: Colors.black.withValues(
                                        alpha: 0.3,
                                      ),
                                      blurRadius: 4.r,
                                      offset: Offset(0, 4.h),
                                    ),
                                  ],
                                ),
                                child: TextButton(
                                  onPressed: () {
                                    Navigator.of(context).pop();
                                    final success =
                                        KiteTeamController.quickJoinTeam(
                                          team.uniqueIdentifier,
                                        );
                                    if (success) {
                                      setState(() {});
                                      KudoToast.showSuccessToast(
                                        context,
                                        'Joined team successfully',
                                      );
                                    }
                                  },
                                  style: TextButton.styleFrom(
                                    shape: RoundedRectangleBorder(
                                      borderRadius: BorderRadius.circular(20.r),
                                    ),
                                  ),
                                  child: Text(
                                    'Join',
                                    style: GoogleFonts.lato(
                                      fontSize: 16.sp,
                                      fontWeight: FontWeight.bold,
                                      color: Colors.black,
                                    ),
                                  ),
                                ),
                              ).configWidget(borderRadius: 20.r),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),

                  Positioned(
                    top: 0.h,
                    right: 0.w,
                    child: GestureDetector(
                      onTap: () => Navigator.of(context).pop(),
                      child: Container(
                        width: 32.w,
                        height: 32.h,
                        decoration: const BoxDecoration(
                          shape: BoxShape.circle,
                          color: Colors.black,
                        ),
                        child: Icon(
                          Icons.close,
                          size: 20.sp,
                          color: Colors.white,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ).configWidget(borderRadius: 24.r),
          ),
    );
  }

  void _showCreateTeamDialog() {
    final currentUser =
        PersonaSessionController.globalInstance.currentPersonaState.value;
    if (currentUser == null) {
      LoginRequiredDialog.show(
        context: context,
        title: 'Login Required',
        message: 'Please login to create teams',
      );
      return;
    }

    showDialog(
      context: context,
      barrierColor: Colors.black.withValues(alpha: 0.8),
      builder:
          (context) => Dialog(
            backgroundColor: Colors.transparent,
            child: Container(
              width: MediaQuery.of(context).size.width - 32.w,
              decoration: BoxDecoration(
                color: Colors.transparent,
                borderRadius: BorderRadius.circular(12.r),
              ),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    'Create Team',
                    style: GoogleFonts.lato(
                      fontSize: 18.sp,
                      fontWeight: FontWeight.bold,
                      color: KudoColors.black,
                    ),
                  ),

                  SizedBox(height: 24.h),

                  Container(
                    decoration: BoxDecoration(
                      color: KudoColors.green,
                      borderRadius: BorderRadius.circular(12.r),
                    ),
                    height: 52.h,
                    child: TextField(
                      controller: _teamDescriptionController,
                      decoration: InputDecoration(
                        hintText: 'Enter team formation declaration',
                        hintStyle: TextStyle(
                          color: Colors.white.withAlpha(128),
                          fontSize: 14.sp,
                        ),
                        border: InputBorder.none,
                        contentPadding: EdgeInsets.symmetric(
                          horizontal: 12.w,
                          vertical: 16.h,
                        ),
                      ),
                    ),
                  ).configWidget(borderRadius: 12.r),

                  SizedBox(height: 16.h),

                  Container(
                    decoration: BoxDecoration(
                      color: KudoColors.green,
                      borderRadius: BorderRadius.circular(12.r),
                    ),
                    height: 52.h,
                    child: TextField(
                      controller: _teamLocationController,
                      decoration: InputDecoration(
                        hintText: 'Input the address you want to go to',
                        hintStyle: TextStyle(
                          color: Colors.white.withAlpha(128),
                          fontSize: 14.sp,
                        ),
                        border: InputBorder.none,
                        contentPadding: EdgeInsets.symmetric(
                          horizontal: 12.w,
                          vertical: 16.h,
                        ),
                      ),
                    ),
                  ).configWidget(borderRadius: 12.r),

                  SizedBox(height: 24.h),

                  Padding(
                    padding: EdgeInsets.symmetric(horizontal: 80.w),
                    child: Container(
                          decoration: BoxDecoration(
                            color: KudoColors.yellow,
                            borderRadius: BorderRadius.circular(25.r),
                          ),
                          height: 48.h,
                          child:
                              Text(
                                'Agree',
                                style: GoogleFonts.lato(
                                  fontSize: 16.sp,
                                  fontWeight: FontWeight.bold,
                                  color: Colors.white,
                                ),
                              ).center(),
                        )
                        .configWidget(borderRadius: 25.r)
                        .inkWell(
                          onTap: () {
                            final description =
                                _teamDescriptionController.text.trim();
                            final location =
                                _teamLocationController.text.trim();

                            if (description.isNotEmpty && location.isNotEmpty) {
                              Navigator.of(context).pop();
                              final success =
                                  KiteTeamController.quickCreateTeam(
                                    teamDescription: description,
                                    locationInfo: location,
                                  );
                              if (success) {
                                setState(() {});
                              }
                              KudoToast.showSuccessToast(
                                context,
                                'Team created successfully',
                              );
                              _teamDescriptionController.clear();
                              _teamLocationController.clear();
                            }
                          },
                        ),
                  ),

                  SizedBox(height: 12.h),

                  Center(
                    child: GestureDetector(
                      onTap: () {
                        Navigator.of(context).pop();
                        _teamDescriptionController.clear();
                        _teamLocationController.clear();
                      },
                      child: Container(
                        width: 48.w,
                        height: 48.h,
                        decoration: BoxDecoration(
                          shape: BoxShape.circle,
                          color: KudoColors.black,
                          border: Border.all(
                            color: KudoColors.grey,
                            width: 1.w,
                          ),
                        ),
                        child: Icon(
                          Icons.close,
                          size: 24.sp,
                          color: Colors.white,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
    );
  }

  Widget _buildTabSection() {
    return Column(
      children: [
        Padding(
          padding: EdgeInsets.symmetric(horizontal: 16.w),
          child: Row(
            children: [
              Expanded(
                child: _buildTabButton(
                  index: 0,
                  title: 'Topic',
                  selectedImage: 'assets/images/topic_selected.png',
                  unselectedImage: 'assets/images/topic.png',
                ),
              ),
              SizedBox(width: 12.w),
              Expanded(
                child: _buildTabButton(
                  index: 1,
                  title: 'Exchange',
                  selectedImage: 'assets/images/exchange_selected.png',
                  unselectedImage: 'assets/images/exchange.png',
                ),
              ),
            ],
          ),
        ),

        SizedBox(height: 16.h),

        _buildDynamicPageView(),

        SizedBox(height: 100.h),
      ],
    );
  }

  Widget _buildTabButton({
    required int index,
    required String title,
    required String selectedImage,
    required String unselectedImage,
  }) {
    final isSelected = _currentTabIndex == index;
    return Container(
      height: 46.h,
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage(isSelected ? selectedImage : unselectedImage),
          fit: BoxFit.fill,
        ),
      ),
    ).inkWell(
      onTap: () {
        _pageController.animateToPage(
          index,
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeInOut,
        );
      },
    );
  }

  Widget _buildDynamicPageView() {
    double contentHeight = _calculateContentHeight();

    return SizedBox(
      height: contentHeight,
      child: PageView(
        controller: _pageController,
        onPageChanged: (index) {
          setState(() {
            _currentTabIndex = index;
          });
        },
        children: [_buildTopicContent(), _buildExchangeContent()],
      ),
    );
  }

  double _calculateContentHeight() {
    if (_currentTabIndex == 0) {
      final topics = KiteTopicController.globalInstance.getAllTopics();
      return topics.length * (140.h + 12.h) + 32.h + 236.h;
    } else {
      final exchanges =
          KiteExchangeController.globalInstance.allExchangesState.value;
      final rows = (exchanges.length / 2).ceil();
      return rows * (188.h + 8.h) + 32.h + 236.h;
    }
  }

  Widget _buildTopicContent() {
    final topics = KiteTopicController.globalInstance.getAllTopics();
    return Column(
      children: topics.map((topic) => _buildTopicItem(topic)).toList(),
    ).paddingHorizontal(16.w);
  }

  Widget _buildTopicItem(KiteTopicEntity topic) {
    return Container(
      width: 343.w,
      height: 140.h,
      margin: EdgeInsets.only(bottom: 12.h),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(12.r),
        image: DecorationImage(
          image: AssetImage(topic.topicImageResource),
          fit: BoxFit.cover,
        ),
      ),
    ).inkWell(
      onTap:
          () => AppNavigationManager.navigateToKiteTopicDetail(context, topic),
    );
  }

  Widget _buildExchangeContent() {
    final exchanges = KiteExchangeController.globalInstance.allExchangesState
        .reactiveValue(context);

    List<Widget> rows = [];
    for (int i = 0; i < exchanges.length; i += 2) {
      List<Widget> rowChildren = [];

      rowChildren.add(Expanded(child: _buildExchangeItem(exchanges[i])));

      if (i + 1 < exchanges.length) {
        rowChildren.add(SizedBox(width: 8.w));
        rowChildren.add(Expanded(child: _buildExchangeItem(exchanges[i + 1])));
      } else {
        rowChildren.add(SizedBox(width: 8.w));
        rowChildren.add(const Expanded(child: SizedBox()));
      }

      rows.add(Row(children: rowChildren));

      if (i + 2 < exchanges.length) {
        rows.add(SizedBox(height: 8.h));
      }
    }

    return Column(children: rows).paddingHorizontal(16.w);
  }

  Widget _buildExchangeItem(KiteExchangeEntity exchange) {
    final publisher = PersonaSessionController.quickGetUserById(
      exchange.publisherPersonaId,
    );
    final isVideo = exchange.mediaType.toString().contains('video');

    return Container(
      height: 188.h,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(20.r),
        image: DecorationImage(
          image: AssetImage(
            isVideo
                ? (exchange.thumbnailResourceUrl ?? exchange.mediaResourceUrl)
                : exchange.mediaResourceUrl,
          ),
          fit: BoxFit.cover,
        ),
      ),
      child: Column(
        children: [
          Align(
            alignment: Alignment.topRight,
            child: Padding(
              padding: EdgeInsets.all(8.w),
              child: ImageResourceHelper.buildSvgIcon(
                svgPath: 'assets/svg/report.svg',
                width: 22.w,
                height: 22.h,
                color: Colors.white,
              ).inkWell(onTap: () => _showReportDialog(exchange)),
            ),
          ),

          const Spacer(),

          if (isVideo)
            Icon(Icons.play_arrow_sharp, size: 40.sp, color: Colors.white),

          const Spacer(),

          ClipRRect(
            borderRadius: BorderRadius.only(
              bottomLeft: Radius.circular(12.r),
              bottomRight: Radius.circular(12.r),
            ),
            child: BackdropFilter(
              filter: ImageFilter.blur(sigmaX: 10.0, sigmaY: 10.0),
              child: Container(
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    begin: Alignment.topCenter,
                    end: Alignment.bottomCenter,
                    colors: [
                      Colors.transparent,
                      Colors.black.withValues(alpha: 0.7),
                    ],
                  ),
                ),
                child: Padding(
                  padding: EdgeInsets.all(8.w),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Text(publisher?.displayAlias ?? 'Unknown')
                          .fontSize(14.sp)
                          .fontWeight(FontWeight.bold)
                          .textColor(Colors.white)
                          .fontFamily(GoogleFonts.lato().fontFamily),

                      SizedBox(height: 2.h),

                      Text(
                        exchange.exchangeDescription,
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                        style: GoogleFonts.lato(
                          fontSize: 12.sp,
                          color: Colors.white,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    ).inkWell(
      onTap:
          () => AppNavigationManager.navigateToKiteExchangeDetail(
            context,
            exchange,
          ),
    );
  }

  void _showReportDialog(KiteExchangeEntity exchange) {
    ReportDialog.show(
      context: context,
      onReport: (reportType) {
        final success = KiteExchangeController.quickDeleteExchange(
          exchange.uniqueIdentifier,
        );
        if (success) {
          KudoToast.showSuccessToast(context, 'Exchange reported successfully');
          setState(() {});
        } else {
          KudoToast.showErrorToast(context, 'Failed to report exchange');
        }
      },
    );
  }

  void _handleUserAvatarTap(PersonaEntity user) {
    final currentUser =
        PersonaSessionController.globalInstance.currentPersonaState.value;

    if (currentUser != null &&
        currentUser.uniqueIdentifier == user.uniqueIdentifier) {
      return;
    }

    AppNavigationManager.navigateToOtherPersonaScreen(context, user);
  }
}
